<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Auth extends BaseController {
	var $_layoutPath = "templates/admin/layout/layout";

	function Auth() {
		parent::BaseController();
		
		$this->_template = $this->settings->item("_admin_template");
		$this->_layout = "simple";
		
		$this->load->library('Form_validation');
		$this->load->library('redux_auth');		
		
		$this->load->helper('url');
		$this->load->helper('form');
		
	}
	
	function index()
	{
		redirect("admin/login");
	}

	function login() {
		if ($this->redux_auth->logged_in())
	    {	
	    	echo "Ya te encuentras logado";
	    }
	    else
	    {
			$this->form_validation->set_rules('email', 'Email Address', 'trim|required|xss_clean');
		    $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
		    
	    	// Set captcha rules if login attempts exceed max attempts in config
			if ($this->redux_auth->is_max_login_attempts_exceeded()){
				$this->form_validation->set_rules('captcha', 'Captcha', 'trim|required|xss_clean|callback_captcha_check');
			}
		    
		    $this->_addData("show_captcha", FALSE);
		    
		    if ($this->form_validation->run() == false)
		    {
		    	if ($this->redux_auth->is_max_login_attempts_exceeded()){
		    		// Create catpcha
					$this->redux_auth->captcha();
					
		    		// Set view data to show captcha on view file
					$this->_addData("show_captcha", TRUE);
		    	}
		        $this->_render();
		    }
		    else
		    {
		        $email    = $this->input->post('email');
		        $password = $this->input->post('password');
		        
		        $login = $this->redux_auth->login($email, $password);
		        
		        if($login !== FALSE){
		        	redirect('admin');
		        } else{
		        	$this->_addError("Usuario no valido");
			        //Comprobaciones de si superamos el limite de intentos fallidos para lanzar el captcha...
			    	if ($this->redux_auth->is_max_login_attempts_exceeded()){
			    		// Create catpcha
						$this->redux_auth->captcha();
					
			    		// Set view data to show captcha on view file
						$this->_addData("show_captcha", TRUE);
			    	}
		        	$this->_render();
		        }
		    }
	    }
		
	}
	
	function captcha_check($code)
	{
		$result = TRUE;
		
		if ($this->redux_auth->is_captcha_expired())
		{
			// Will replace this error msg with $lang
			$this->form_validation->set_message('captcha_check', 'Tu codigo de confirmación ha expirado. Intentalo de nuevo.');			
			$result = FALSE;
		}
		elseif ( ! $this->redux_auth->is_captcha_match($code))
		{
			$this->form_validation->set_message('captcha_check', 'Tu codigo de confirmación no es correcto. Intentalo de nuevo.');			
			$result = FALSE;
		}

		return $result;
	}

	function logout() {
		$this->redux_auth->logout();
		redirect('admin');
	}
	
}
?>